package com.zzh.takeoutapp.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.github.florent37.viewanimator.ViewAnimator;
import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.CarAdapter;
import com.zzh.takeoutapp.adapter.OrderFragmentAdapter;
import com.zzh.takeoutapp.base.BaseActivity;
import com.zzh.takeoutapp.behaviors.AppBarBehavior;
import com.zzh.takeoutapp.dialog.SpecDialogFragment;
import com.zzh.takeoutapp.entity.CutStyleEntity;
import com.zzh.takeoutapp.entity.FoodBean;
import com.zzh.takeoutapp.entity.OrderListBean;
import com.zzh.takeoutapp.entity.TypeBean;
import com.zzh.takeoutapp.event.FoobEvent;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.fragment.EvaluateFragment;
import com.zzh.takeoutapp.fragment.FirstFragment;
import com.zzh.takeoutapp.fragment.MerchantFragment;
import com.zzh.takeoutapp.model.ModelUtil;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.ColorUtil;
import com.zzh.takeoutapp.utils.GsonResolve;
import com.zzh.takeoutapp.utils.ImageManager;
import com.zzh.takeoutapp.utils.LoadingUtil;
import com.zzh.takeoutapp.utils.ToolBarHelper;
import com.zzh.takeoutapp.utils.UtilTool;
import com.zzh.takeoutapp.view.goods.AddWidget;
import com.zzh.takeoutapp.view.goods.ShopCarView;
import com.zzh.takeoutapp.view.goods.ShopInfoContainer;
import com.zzh.takeoutapp.view.goods.ViewUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/19.
 */

public class OrderCarDatelisActivity extends BaseActivity implements AddWidget.OnAddClick {
    @Bind(R.id.iv_add_collect)
    ImageView iv_add_collect;//添加收藏
    View scroll_container;
    @Bind(R.id.toolbar)
    Toolbar tbToolbar;
    @Bind(R.id.rootview)
    CoordinatorLayout rootview;
    @Bind(R.id.car_mainfl)
    ShopCarView shopCarView;
    @Bind(R.id.car_recyclerview)
    RecyclerView carRecView;
    @Bind(R.id.indicator)
    TabLayout mTabLayout;
    @Bind(R.id.viewpager)
    ViewPager mViewPager;
    @Bind(R.id.shopcontainer)
    ShopInfoContainer shopInfoContainer;
    public static final String ORDER_CAR_DATELIS = "OrderCarDatelis";
    private final String MERCHANT_FRAGMENT = "MerchantFragment";
    private final String EVALUATE = "EvaluateFragment";
    private final String ADD_COLLECT_SERVICE = "AddCollectSerVice";
    public BottomSheetBehavior behavior;
    public FirstFragment firstFragment;
    public static CarAdapter carAdapter;
    private List<Fragment> fragmentList;//添加的list
    public OrderFragmentAdapter adapter;
    public List<String> stringList;
    public static List<TypeBean> typeBean;
    public static List<FoodBean> foodBeanDatas;
    public String Shop_id;
    public StringBuffer buffer;
    private LoadingUtil loadingUtil;
    private String Cate_id;
    private boolean dealCar = false;
    private OrderListBean orderListBean;
    private SpecDialogFragment addUserDialogFragment;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void setContent() {
        setContentView(R.layout.activity_order_details);
        ButterKnife.bind(this);
        loadingUtil = new LoadingUtil(this);
        scroll_container = findViewById(R.id.scroll_container);
    }

    private void initViews() {
        initViewpager();
        initShopCar();
    }

    public void expendCut(View view) {
        float cty = scroll_container.getTranslationY();
        if (!ViewUtils.isFastClick()) {
            ViewAnimator.animate(scroll_container)
                    .translationY(cty, cty == 0 ? AppBarBehavior.cutExpHeight : 0)
                    .decelerate()
                    .duration(100)
                    .start();
        }
    }

    private void initShopCar() {
        behavior = BottomSheetBehavior.from(findViewById(R.id.car_container));
        View blackView = findViewById(R.id.blackview);
        shopCarView.setBehavior(behavior, blackView);
        carRecView.setLayoutManager(new LinearLayoutManager(this));
        ((DefaultItemAnimator) carRecView.getItemAnimator()).setSupportsChangeAnimations(false);
        carAdapter = new CarAdapter(new ArrayList<FoodBean>(), this);
        carAdapter.bindToRecyclerView(carRecView);
    }

    private void initViewpager() {
        fragmentList = new ArrayList<>();
        firstFragment = new FirstFragment();
        fragmentList.add(firstFragment);
        fragmentList.add(EvaluateFragment.newInstance());
        fragmentList.add(MerchantFragment.newInstance(Shop_id));
        stringList = new ArrayList<>();
        ColorUtil.reflex(mTabLayout);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setTabTextColors(getResources().getColor(R.color.black_divider),
                //mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
                getResources().getColor(R.color.yellow));
        mTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.yellow));
        mTabLayout.setSelectedTabIndicatorHeight(5);
        mViewPager.setOffscreenPageLimit(3);
        mTabLayout.setupWithViewPager(mViewPager);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(FoobEvent event) {
        String msgType = (String) event.getMsgType();
        switch (msgType) {
            case "dealCar":
                FoodBean foodBean = event.getBean();
                int p = event.getPosition();
                if (firstFragment.getFoodAdapter().getItem(p).getSelectCount() == 0) {
                    carAdapter.addData(foodBean);
                    dealCar = true;
                }
                dealCar(foodBean);
                break;
            case "SpecDialogFragment"://选规格
                addUserDialogFragment = SpecDialogFragment.getInstence();
                FoodBean foodBean1 = event.getBean();
                addUserDialogFragment.setFoodBean(foodBean1);
                addUserDialogFragment.setOnAddClick(this);
                addUserDialogFragment.setdAdapter(carAdapter);
                if (!addUserDialogFragment.isAdded()) {
                    addUserDialogFragment.show(getSupportFragmentManager(), "");
                }
                break;
            case "clearCar":
                clearCar();
                break;
        }
    }

    private void dealCar(FoodBean foodBean) {
        HashMap<String, Long> typeSelect = new HashMap<>();//更新左侧类别badge用
        BigDecimal amount = new BigDecimal(0.0);
        int total = 0;
        boolean hasFood = false;
        if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            firstFragment.getFoodAdapter().notifyDataSetChanged();
        }
        List<FoodBean> flist = carAdapter.getData();
        List<FoodBean> foodBeanList = firstFragment.getFoodAdapter().getData();
        int p = -1;
        for (int i = 0; i < flist.size(); i++) {
            FoodBean fb = flist.get(i);
            if (fb.getProduct_id().equals(foodBean.getProduct_id())) {
                fb = foodBean;
                hasFood = true;
                if (foodBean.getSelectCount() == 0) {
                    p = i;
                } else {
                    carAdapter.setData(i, foodBean);
                }
            }
            total += fb.getSelectCount();
            if (foodBean.getSpecsX() != null && foodBean.getSpecsX().size() > 0) {
                String[] split = foodBean.getProduct_id().split(foodBean.getSpecsX().get(0).getSpec_id());
                for (FoodBean foodBean1 : foodBeanList) {
                    if (foodBean1.getProduct_id().equals(split[0])) {
                        if (typeSelect.containsKey(foodBean1.getType())) {
                            typeSelect.put(foodBean1.getType(), typeSelect.get(foodBean1.getType()) + fb.getSelectCount());
                        } else {
                            typeSelect.put(foodBean1.getType(), fb.getSelectCount());
                        }
                    }
                }
            } else if (foodBean.getSpecification() != null && foodBean.getSpecification().size() > 0) {
                String[] split = foodBean.getProduct_id().split(foodBean.getSpecification().get(0).getKey());
                for (FoodBean foodBean1 : foodBeanList) {
                    if (foodBean1.getProduct_id().equals(split[0])) {
                        if (typeSelect.containsKey(foodBean1.getType())) {
                            typeSelect.put(foodBean1.getType(), typeSelect.get(foodBean1.getType()) + fb.getSelectCount());
                        } else {
                            typeSelect.put(foodBean1.getType(), fb.getSelectCount());
                        }
                    }
                }
            } else {
                for (FoodBean foodBean1 : foodBeanList) {
                    if (foodBean1.getProduct_id().equals(fb.getProduct_id())) {
                        if (typeSelect.containsKey(foodBean1.getType())) {
                            typeSelect.put(foodBean1.getType(), typeSelect.get(foodBean1.getType()) + fb.getSelectCount());
                        } else {
                            typeSelect.put(foodBean1.getType(), fb.getSelectCount());
                        }
                        foodBean1.setSelectCount(fb.getSelectCount());
                    }
                }
            }
            amount = amount.add(fb.getPrice().multiply(BigDecimal.valueOf(fb.getSelectCount())));
        }
        if (p >= 0) {
            carAdapter.remove(p);
        } else if (!hasFood && foodBean.getSelectCount() > 0) {
            if (dealCar == false)
                carAdapter.addData(foodBean);
            if (typeSelect.containsKey(foodBean.getType())) {
                typeSelect.put(foodBean.getType(), typeSelect.get(foodBean.getType()) + foodBean.getSelectCount());
            } else {
                typeSelect.put(foodBean.getType(), foodBean.getSelectCount());
            }
            amount = amount.add(foodBean.getPrice().multiply(BigDecimal.valueOf(foodBean.getSelectCount())));
            total += foodBean.getSelectCount();
        }
        shopCarView.showBadge(total);
        firstFragment.getTypeAdapter().updateBadge(typeSelect);
        shopCarView.updateAmount(amount);
        firstFragment.getFoodAdapter().notifyDataSetChanged();
    }

    public void clearCar(View view) {
        ViewUtils.showClearCar(this, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                clearCar();
            }
        });
    }

    private void clearCar() {
        List<FoodBean> flist = carAdapter.getData();
        for (int i = 0; i < flist.size(); i++) {
            FoodBean fb = flist.get(i);
            fb.setSelectCount(0);
        }
        carAdapter.setNewData(new ArrayList<FoodBean>());
        List<FoodBean> foodBeanList = firstFragment.getFoodAdapter().getData();
        for (FoodBean foodBean1 : foodBeanList) {
            foodBean1.setSelectCount(0);
        }
        shopCarView.showBadge(0);
        if (addUserDialogFragment != null) {
            addUserDialogFragment.foodKeyList.clear();
            addUserDialogFragment.stringList.clear();
            addUserDialogFragment.list1.clear();
            addUserDialogFragment.stringStringMap.clear();
        }
        firstFragment.getFoodAdapter().notifyDataSetChanged();
        firstFragment.getTypeAdapter().updateBadge(new HashMap<String, Long>());
        shopCarView.updateAmount(new BigDecimal(0.0));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void initComponent() {
        if (getIntent().getSerializableExtra("orderListBean") != null) {
            orderListBean = (OrderListBean) getIntent().getSerializableExtra("orderListBean");
            ServiceUrl.ShopDetailServiceUrl(this, orderListBean.getShop_id(), ORDER_CAR_DATELIS);
        } else {
            ServiceUrl.ShopDetailServiceUrl(this, getIntent().getStringExtra("shop_id"), ORDER_CAR_DATELIS);
        }
        ToolBarHelper.setTitleAndBackAndText(this, tbToolbar, "");
        initViews();
        loadingUtil.startShowLoading();
    }

    @Override
    public void setListener() {
        shopCarView.setmOnItemClickLitener(new ShopCarView.OnItemClickListener() {
            @Override
            public void onItemClick(View v) {
                List<FoodBean> foodBeanList = firstFragment.getFoodAdapter().getData();
                List<FoodBean> data = carAdapter.getData();
                if (data.size() != 0) {
                    buffer = new StringBuffer();
                    for (int i = 0; i < data.size(); i++) {
                        FoodBean foodBean = data.get(i);
                        Shop_id = data.get(i).getShop_id();
                        Cate_id = data.get(i).getCate_id();
                        if (foodBean.getSpecsX() != null && foodBean.getSpecsX().size() > 0) {
                            String[] split = foodBean.getProduct_id().split(foodBean.getSpecsX().get(0).getSpec_id());
                            String Product_id = split[0];
                            long selectCount = 0;
                            for (FoodBean foodBean1 : foodBeanList) {
                                if (foodBean1.getProduct_id().equals(split[0])) {
                                    selectCount = foodBean1.getSelectCount();
                                    break;
                                }
                            }
                            String spec_id = foodBean.getSpec_id_next();
                            Map<String, String> stringStringMap = foodBean.getStringStringMap();
                            String SpecsName = "";
                            for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
                                SpecsName = entry.getKey() + "_" + entry.getValue() + "-";
                            }
                            buffer.append(Product_id + ":" + spec_id + ":" + selectCount + "&-" + SpecsName + ",");

                        } else if (foodBean.getSpecification() != null && foodBean.getSpecification().size() > 0) {
                            String[] split = foodBean.getProduct_id().split(foodBean.getSpecification().get(0).getKey());
                            String Product_id = split[0];
                            long selectCount = 0;
                            for (FoodBean foodBean1 : foodBeanList) {
                                if (foodBean1.getProduct_id().equals(split[0])) {
                                    selectCount = foodBean1.getSelectCount();
                                    break;
                                }
                            }
                            String spec_id = foodBean.getSpec_id_next();
                            Map<String, String> stringStringMap = foodBean.getStringStringMap();
                            String SpecsName = "";
                            for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
                                SpecsName = entry.getKey() + "_" + entry.getValue() + "-";
                            }
                            buffer.append(Product_id + ":" + spec_id + ":" + selectCount + "&-" + SpecsName + ",");
                        } else {
                            String Product_id = data.get(i).getProduct_id();
                            long selectCount = data.get(i).getSelectCount();
                            String Is_discount = data.get(i).getIs_discount();
                            buffer.append(Product_id + ":" + Is_discount + ":" + selectCount + "&,");
                        }
                        String substring = buffer.toString().substring(0, buffer.toString().length() - 1);
                        Log.e("substring---", substring);
                        Intent intent = new Intent();
                        intent.setClass(OrderCarDatelisActivity.this, SubmitOrderActivity.class);
                        intent.putExtra("Shop_id", Shop_id);
                        intent.putExtra("buffer", substring);
                        start_Activity(intent);
                    }
                }
            }
        });
    }

    private static String getValue(Map<Integer, String> map) {
        String value = "";
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            value = (String) entry.getValue();
        }
        return value;
    }

    private static Integer getKey(Map<Integer, String> map) {
        Integer value = 0;
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            value = (Integer) entry.getKey();
        }
        return value;
    }

    @Override
    public void onAfterInit() {
    }

    @OnClick({R.id.iv_add_collect})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.iv_add_collect:
                loadingUtil.startShowLoading();
                ServiceUrl.AddCollectSerVice(this, "waimai",
                        getIntent().getStringExtra("cate_id"), ADD_COLLECT_SERVICE);
                break;
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        EventbusHelper.register(this);
    }

    @Override
    public void onStop() {
        EventbusHelper.unregister(this);
        loadingUtil.stopShowLoading();
        super.onStop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(NetMsgEvent event) {
        String _msgType = (String) event.getMsgType();
        JSONObject jsonObject = event.getMsgJSONObj();
        switch (_msgType) {
            case ORDER_CAR_DATELIS:
                if (jsonObject != null)
                    if (jsonObject.optString("error").equals("0")) {
                        loaderData(jsonObject);
                    }
                break;
            case MERCHANT_FRAGMENT:
                break;
            case ADD_COLLECT_SERVICE:
                if (jsonObject != null) {
                    loadingUtil.stopShowLoading();
                    UtilTool.toast(this, jsonObject.optString("message"));
                }
                break;
        }
    }

    private void loaderData(JSONObject jsonObject) {
        JSONObject data = jsonObject.optJSONObject("data");
        JSONObject detail = data.optJSONObject("detail");
        String comment_num = data.optString("comment_num");
        stringList.add("点菜");
        stringList.add("评价(" + comment_num + ")");
        stringList.add("商家");
        adapter = new OrderFragmentAdapter(getSupportFragmentManager(), fragmentList, stringList);
        ServiceUrl.MerchantService(this, detail.optString("shop_id"), MERCHANT_FRAGMENT);
        ServiceUrl.CommentsServiceUrl(this, EVALUATE);
        ImageManager.loadUrlImage(this, detail.optString("logo"), shopInfoContainer.iv_shop);
        shopInfoContainer.shop_name.setText(detail.optString("title"));
        shopInfoContainer.shop_sum.setText("公告:" + detail.optString("delcare"));
        Shop_id = detail.optString("shop_id");
        typeBean = ModelUtil.getTypeBean(jsonObject);
        foodBeanDatas = ModelUtil.getFoodBeanDatas(jsonObject);
        JSONArray jsonArray = detail.optJSONArray("huodong");
        List<CutStyleEntity> cutStyleEntities = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject object = jsonArray.optJSONObject(i);
            CutStyleEntity cutStyleEntity = GsonResolve.jsonString2Bean(object.toString(), CutStyleEntity.class);
            cutStyleEntities.add(cutStyleEntity);
        }
        mViewPager.setAdapter(adapter);
        loadingUtil.stopShowLoading();
        adapter.notifyDataSetChanged();
        if (getIntent().getSerializableExtra("orderListBean") != null) {
            dealCar = false;
            List<OrderListBean.ProductsBean> orderListBeanProducts = orderListBean.getProducts();
            List<FoodBean> foodBeans = firstFragment.getFoodAdapter().getData();
            for (int i = 0; i < orderListBeanProducts.size(); i++) {
                OrderListBean.ProductsBean productsBean = orderListBeanProducts.get(i);
                for (int j = 0; j < foodBeans.size(); j++) {
                    FoodBean foodBean = foodBeans.get(j);
                    if (foodBean.getProduct_id().equals(productsBean.getProduct_id())) {
                        foodBean.setSelectCount(Long.parseLong(productsBean.getProduct_number()));
                        dealCar(foodBean);
                    }
                }
            }
            firstFragment.getFoodAdapter().notifyDataSetChanged();
        }

    }

    @Override
    public void onAddClick(View view, FoodBean fb, FoodBean foodBean1) {
        dealCar = false;
        if (fb.getSpecsX().size() == 0 && fb.getSpecification().size() == 0) {
            dealCar(fb);
        } else {
            dealCar(foodBean1);
        }
        ViewUtils.addTvAnim(view, shopCarView.carLoc, this, rootview);
    }

    @Override
    public void onSubClick(FoodBean fb, FoodBean foodBean1) {
        dealCar = false;
        if (fb.getSpecsX().size() == 0 && fb.getSpecification().size() == 0) {
            dealCar(fb);
        } else {
            dealCar(foodBean1);
        }
    }
}


